package cn.hackcloud.mutithread;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 生产者消费者阻塞队列版
 */
public class ProducerConsumerBlockQueueDeomo {
    public static void main(String[] args) throws InterruptedException {
        MyResource myResource = new MyResource(new ArrayBlockingQueue<>(3));
        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + "生产者线程启动");
            try {
                myResource.producer();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }, "producer").start();

        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + "消费者线程启动");
            try {
                myResource.consumer();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }, "consumer").start();

        TimeUnit.SECONDS.sleep(5);
        System.out.println(Thread.currentThread().getName() + "5秒钟时间到、大老板叫停");
        myResource.stop();
    }
}

class MyResource {
    private volatile boolean flag = true;//默认开启 、进行生产消费
    private AtomicInteger atomicInteger = new AtomicInteger();
    private BlockingQueue<String> blockingQueue;

    public MyResource(BlockingQueue<String> blockingQueue) {
        this.blockingQueue = blockingQueue;
        System.out.println("blockingQueue = " + blockingQueue.getClass().getName());
    }

    public void stop() {
        flag = false;
    }

    public void producer() throws Exception {
        String data = null;
        boolean isSuccess;
        while (flag) {
            data = atomicInteger.incrementAndGet() + "";
            isSuccess = blockingQueue.offer(data, 2, TimeUnit.SECONDS);
            if (isSuccess) {
                System.out.println(Thread.currentThread().getName() + "：插入队列" + data + "成功！");
            } else {
                System.out.println(Thread.currentThread().getName() + "：插入队列" + data + "失败！");
            }
            TimeUnit.SECONDS.sleep(1);
        }
        System.out.println(Thread.currentThread().getName() + "大老板叫停、表示flag=false,生产动作结束！");

    }

    public void consumer() throws Exception {
        String result = null;
        while (flag) {
            result = blockingQueue.poll(2l, TimeUnit.SECONDS);

            if (null == result || result.equalsIgnoreCase("")) {
                flag = false;
                System.out.println(Thread.currentThread().getName() + "：超过2秒没取到数据消费者退出！");
                return;
            }
            System.out.println(Thread.currentThread().getName() + "：消费队列成功！");

        }
    }
}